<template>
	<div class="ui-clamp">
		<input 
			:id="clampUnique" 
			class="ui-clamp_input" 
			type="checkbox" 
			:checked="isOpen" 
			@change="checkChange" 
		/>
		<div ref="textElement" class="ui-clamp_text" :style="{ '-webkit-line-clamp': line }">
			<label v-show="isOver" :for="clampUnique" class="ui-clamp_text-btn"></label>
			<slot></slot>
		</div>
	</div>
</template>

<script>
	
	let clampUniqueSeed = 0;
	
</script>

<script setup>
	
	import { defineComponent, unref, ref, watch, computed, onMounted } from 'vue';
	
	const props = defineProps({
		line: {
			type: Number,
			default: 2
		}
	})
	
	const emits = defineEmits(['open', 'close']);
	
	const textElement = ref();
	
	const isOpen = ref(false);
	const isOver = ref(false);
	
	const clampUnique = `UICLAMP_UNIQUE_${clampUniqueSeed++}`;
	
	onMounted(() => {
		const { offsetHeight, scrollHeight } = unref(textElement);
		isOver.value = scrollHeight > offsetHeight;
	})
	
	function checkChange(e) {
		const { checked } = e.target;
		isOpen.value = checked;
		emits(checked ? 'open' : 'close');
	}
	
</script>

<style lang="scss" scoped>
	
	.ui-clamp {
		display: flex;
	}
	
	.ui-clamp_input {
		display: none;
		&:checked+.ui-clamp_text {
			display: block;
			.ui-clamp_text-btn::after {
				content: '收起';
			}
		}
		&:not(:checked)+.ui-clamp_text {
			display: -webkit-box;
			-webkit-box-orient: vertical;
			.ui-clamp_text-btn::after {
				content: '展开';
			}
		}
	}
	
	.ui-clamp_text {
		overflow: hidden;
		text-overflow: ellipsis;
		word-break: break-all;
		&::before {
			float: right;
			content: '';
			width: 0;
			height: 100%;
			margin-bottom: -1em;
		}
	}
	
	.ui-clamp_text-btn {
		float: right;
		clear: both;
		cursor: pointer;
		transform: translateY(calc(-100% + 1em));
		color: #409eff;
		margin-left: 6px;
	}
	
</style>